package com.snowy.hidden.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Slf4j
public class AliyunOssUtil {
    /**
     * 默认OSS取回地址
     */
    public static final String DEFAULT_URL_HEAD = "https://lineinspection.oss-cn-chengdu.aliyuncs.com/";

    /**
     * 上传文件到阿里云OSS
     *
     * @param fileName
     * @param ins
     * @return
     */
    public static String uploadOss(String fileName, InputStream ins) {
        String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
        String accessKeyId = "LTAI5tPLWZ3V9BxEi8bcY7cx";
        String accessKeySecret = "KRw1AsCq41HHwzrztkQW26IsFPiTCC";
        String bucketName = "lineinspection";
        String returnUrl = "";
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, ins);
            // 关闭OSSClient。
            ossClient.shutdown();
            returnUrl = DEFAULT_URL_HEAD+fileName;
        } catch (Exception e) {
            log.error("==uploadOss==",e);
        }
        return returnUrl;
    }



    /**
     * 生成文件的key，格式如 2021/10/11/1377109572375810050.docx
     *
     * @author xuyuxiang
     * @date 2022/4/22 15:58
     **/
    public static String genFileKey(MultipartFile file) {

        // 获取文件原始名称
        String originalFileName = file.getOriginalFilename();

        // 获取文件后缀
        String fileSuffix = FileUtil.getSuffix(originalFileName);

        // 生成文件的对象名称，格式如:1377109572375810050.docx
        String fileObjectName = IdWorker.getIdStr() + StrUtil.DOT + fileSuffix;

        // 获取日期文件夹，格式如，2021/10/11/
        String dateFolderPath = DateUtil.thisYear() + StrUtil.SLASH +
                (DateUtil.thisMonth() + 1) + StrUtil.SLASH +
                DateUtil.thisDayOfMonth() + StrUtil.SLASH+"APP"+StrUtil.SLASH;

        // 返回
        return dateFolderPath + fileObjectName;
    }

}
